<?php
/**
 * 微信登录回调处理
 */

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 读取配置
$config = include __DIR__ . '/../../config.php';
$wechatConfig = $config['plugins']['wechat'] ?? [];

if (empty($wechatConfig['enabled']) || !$wechatConfig['enabled']) {
    die('微信登录服务未启用');
}

// 获取回调参数
$code = $_GET['code'] ?? '';
$state = $_GET['state'] ?? '';

if (empty($code)) {
    die('授权失败：缺少code参数');
}

// 验证state参数（防CSRF）
if (empty($_SESSION['wechat_state']) || $state !== $_SESSION['wechat_state']) {
    die('授权失败：state参数验证失败');
}

unset($_SESSION['wechat_state']);

$appId = $wechatConfig['app_id'];
$appSecret = $wechatConfig['app_secret'];

try {
    // 1. 通过code换取access_token
    $tokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . http_build_query([
        'appid' => $appId,
        'secret' => $appSecret,
        'code' => $code,
        'grant_type' => 'authorization_code'
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $tokenUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $tokenData = json_decode($response, true);
    
    if (isset($tokenData['errcode'])) {
        die('获取access_token失败：' . ($tokenData['errmsg'] ?? '未知错误'));
    }
    
    $accessToken = $tokenData['access_token'] ?? '';
    $openid = $tokenData['openid'] ?? '';
    
    if (empty($accessToken) || empty($openid)) {
        die('获取access_token失败：响应数据不完整');
    }
    
    // 2. 获取用户信息
    $userInfoUrl = 'https://api.weixin.qq.com/sns/userinfo?' . http_build_query([
        'access_token' => $accessToken,
        'openid' => $openid
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $userInfoUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $userInfo = json_decode($response, true);
    
    if (isset($userInfo['errcode'])) {
        die('获取用户信息失败：' . ($userInfo['errmsg'] ?? '未知错误'));
    }
    
    $nickname = $userInfo['nickname'] ?? '微信用户';
    $unionid = $userInfo['unionid'] ?? $openid;
    
    // 3. 检查是否与管理员配置中的微信号匹配
    $adminWechatId = $config['admin_user']['wechat_id'] ?? '';
    
    if (empty($adminWechatId)) {
        die('管理员未配置微信号，无法使用微信登录');
    }
    
    // 匹配 openid 或 unionid
    $isAuthorized = false;
    if ($adminWechatId === $openid || $adminWechatId === $unionid) {
        $isAuthorized = true;
    }
    
    if (!$isAuthorized) {
        die('该微信账号未授权登录，请联系管理员<br>当前 OpenID: ' . htmlspecialchars($openid) . '<br>UnionID: ' . htmlspecialchars($unionid));
    }
    
    // 4. 设置登录session
    $_SESSION['logged_in'] = true;
    $_SESSION['username'] = $config['admin_user']['username']; // 使用管理员配置的用户名
    $_SESSION['wechat_openid'] = $openid;
    $_SESSION['wechat_unionid'] = $unionid;
    $_SESSION['login_type'] = 'wechat';
    
    // 5. 跳转到首页
    header('Location: ../../index.php');
    exit;
    
} catch (Exception $e) {
    die('登录失败：' . $e->getMessage());
}
